package charlie.shop.web;

import com.charlie.beans.Product;
import com.charlie.sessions.ProductFacadeLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.persistence.NoResultException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Display item information servlet 
 * 
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@WebServlet(name = "ItemServlet", urlPatterns = {"/item/*"})
public class ItemServlet extends HttpServlet {
    @EJB
    private ProductFacadeLocal productFacade;
    
    /**
     * Return item description by id
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String arg = request.getPathInfo().substring(1);
        Product item = null;
        if (arg.length() > 0) {
            try {
                Integer item_id = Integer.valueOf(arg);
                item = productFacade.find(item_id);
            } catch(NumberFormatException ex) {
                // wrong item id
            } catch(NoResultException ex) {
                // item not found
            }
        }
        request.setAttribute("item", item);
        getServletContext().getRequestDispatcher("/item.jsp").forward(request, response);
    }   
}
